import {genkit} from 'genkit';
import {googleAI} from '@genkit-ai/googleai';
import axios from 'axios';
import OpenAI from 'openai';
import os from 'os';

export const ai = genkit({
    promptDir: './prompts',
    plugins: [
        googleAI({
            apiKey: process.env.GOOGLE_GENAI_API_KEY,
        }),
    ],
    model: 'googleai/gemini-2.0-flash',
});
const openaiVolcengine = new OpenAI({
    apiKey: '5b93c18c-cc8c-4d27-8905-9004a23178cb',
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
});

export async function* sendVolcengine(prompt: string) {
    console.log('----- streaming request -----');
    const stream = await openaiVolcengine.chat.completions.create({
        messages: [
            {role: 'system', content: 'You are a helpful assistant.'},
            {role: 'user', content: prompt},
        ],
        model: process.env.VOLCENGINE_MODEL ||'ep-20250413175840-vqjnd',
        max_tokens: 12288 , // 根据isReasoningOn调整回答长度
        stream: true,
    });

    for await (const part of stream) {
        const content = part.choices[0]?.delta?.content || '';
        yield content; // 逐步返回响应内容
    }
}

export async function* openApiLocal(prompt: string, isReasoningOn: boolean) {
    const url = "http://122.11.227.206:8000/v1/chat/completions";
    const data = {
        model: "DeepSeek-R1",
        messages: [
            {role: 'system', content: 'You are a helpful assistant.'},
            {role: "user", content: prompt},
        ],
        temperature: isReasoningOn ? 0.7 : 0.3,  // 根据isReasoningOn调整创造性
        max_tokens: isReasoningOn ? 100000 : 2000, // 根据isReasoningOn调整回答长度
        top_p: isReasoningOn ? 0.9 : 0.5,       // 根据isReasoningOn调整多样性
        presence_penalty: isReasoningOn ? 0.6 : 0.2,  // 根据isReasoningOn调整探索新思路的鼓励程度
        stream: true, // 启用流式响应
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                "Content-Type": "application/json",
            },
            responseType: 'stream', // 设置响应类型为流
        });

        let buffer = '';
        for await (const chunk of response.data) {
            buffer += chunk.toString();
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留未处理完的部分

            for (const line of lines) {
                if (line.trim() === '') continue;
                try {
                    const jsonString = line.replace(/^data: /, '');
                    if (jsonString === '[DONE]') break;
                    const json = JSON.parse(jsonString);
                    const content = json.choices[0]?.delta?.content || '';
                    yield content;
                } catch (error) {
                    console.error('Error parsing JSON:', error);
                }
            }
        }
    } catch (error) {
        console.error('Error calling API:', error);
        throw error;
    }
}

